import 'package:elephant_fish/http/core/hi_error.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/user_member_request.dart';
import 'package:elephant_fish/model/family_entity.dart';
import 'package:elephant_fish/model/family_member_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/family_member.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class FamilyMemberPage extends StatefulWidget {
  const FamilyMemberPage({Key key}) : super(key: key);

  @override
  _FamilyMemberPageState createState() => _FamilyMemberPageState();
}

class _FamilyMemberPageState extends State<FamilyMemberPage> {

  ScrollController _scrollController = ScrollController();
  int pageIndex = 1;
  bool _loading = false;
  List<FamilyMemberEntity> familyEntitys;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      appBar: AppBar(
        backgroundColor: Color(0xff140c3d),
        centerTitle: true,
        leading: GestureDetector(
          child: Icon(
            Icons.arrow_back_ios,
            size: SizeUtil.px(32),
            color: Color(0xfff3f3f3),
          ),
          onTap: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          '家族详情',
          style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff5f5f5)),
        ),
      ),
      body: ListView.builder(
          itemCount: familyEntitys == null ? 0 : familyEntitys.length,
          controller: _scrollController,
          shrinkWrap: true,
          itemBuilder: (context, index) {
            return FamilyMember(familyEntity: familyEntitys[index],);
          }),
    );
  }

  Future<void> _loadData({loadMore = false}) async {
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String appToken = prefs.getString('app-token');
      BaseRequest request = UserMemeberRequest();
      request
          .add('page', currentIndex)
          .addHeader('usertoken', appToken);
      var result = await HiNet.getInstance().fire(request);
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(
              arguments: {'loginCode': '-1'},
            );
          },
        ));
      } else if (result['code'] == 0) {
        List<Map<String, dynamic>> listMap =
        new List<Map<String, dynamic>>.from(result['data']['data']);
        List<FamilyMemberEntity> list = List();
        for (int i = 0; i < listMap.length; i++) {
          list.add(FamilyMemberEntity.fromJson(listMap[i]));
        }
        setState(() {
          if (loadMore) {
            if (list.isNotEmpty) {
              //合成一个新数组
              familyEntitys = [...familyEntitys, ...list];
              pageIndex++;
            }
          } else {
            familyEntitys = list;
          }
        });
        Future.delayed(Duration(milliseconds: 1000), () {
          _loading = false;
        });
      }
    } on NeedAuth catch (e) {
      print(e);
    } on HiNetError catch (e) {
      print(e);
    }
  }
}
